from django.core.management.base import BaseCommand, CommandError
from apps.order.models import *
from apps.message.models import *
from apps.product.models import *
from apps.repo.models import *
from datetime import timedelta
import time
from django.db import transaction
import sys
from apps.message.models import *
from sdks.getui import GetuiClient

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('product_id', type=str)

    def handle(self, *args, **options):
        start_time = time.time()
        product_id = options.get('product_id')
        product = Product.objects.get(pk=product_id)
        gbs = GoodsBlock.objects.filter(product_id=product_id)
        # product.stock = gbs.count()
        product.publish_count = gbs.count()
        product.save()
        gbcs = []

        for gb in gbs:
            # 预售节点
            gbc = GoodsBlockChain(
                goods_block=gb,
                operator_user_id=None,
                chain_type=GoodsBlockChain.ChainType.PRE_SALE.name,
                node_datetime=datetime.now(),
                storage_repo_id=gb.repo_id,
                storage_repo_days=0
            )
            gbc_op = gbc.get_block_chain_node_outputs()
            gbc.title = gbc_op['title']
            gbc.contents = gbc_op['contents']
            gbc.repo_info = gbc_op['repo_info']

            gbcs.append(gbc)
        with transaction.atomic():
            GoodsBlockChain.objects.bulk_create(gbcs)
            # 产品预售消息
            product_pre_sale_start_end = '%s-%s' % (
                product.pre_sale_start_time.strftime('%Y.%m.%d'), product.pre_sale_end_time.strftime('%m.%d'))
            msg = Message.objects.create(
                title="产品预售",
                content="%s开启%s预售，预售时间为：%s，敬请关注！" % (product.brand.name, product.name, product_pre_sale_start_end),
                msg_type=Message.MsgType.PRE_SALE,
            )
            cids = []
            for u in User.objects.all():
                uum, created = UserUnreadMessage.objects.get_or_create(user_id=u.pk)
                if created:
                    uum.unread_message_ids = {e[0]: [] for e in Message.MsgType.get_choices()}
                    uum.last_message_id = {e[0]: '' for e in Message.MsgType.get_choices()}
                    uum.save()
                uum.unread_message_ids[Message.MsgType.PRE_SALE.name].append(msg.pk)
                uum.last_message_id[Message.MsgType.PRE_SALE.name] = msg.pk
                uum.save()
                if u.getui_clientid:
                    cids.append(u.getui_clientid)

            getui = GetuiClient()
            status_code, rs = getui.push_list_transmission_save_list_body(
                transmission_content=msg.make_transmission_msg(),
                transmission_type=True,
            )
            if type(rs) == dict and rs['result'] == 'ok':
                taskid = rs['taskid']
                getui.push_list_transmission(cids, taskid, need_detail=False)



        end_time = time.time()
        print('Count: %d Success: %d Times: %f' % (len(gbs), len(gbcs), end_time-start_time))
